<?php

/**
 * 积分类
 * Date: 2018/11/21
 */

namespace Lib\Paas;

use Lib\Base\Validate;

class Point extends Base
{
    public function __construct($sData = [])
    {
        parent::__construct($sData);
    }

    /**
     * 查询积分(支持批量查询)
     * @param string|array  $pointId【必填】 积分ID，如果是查询多个积分，积分ID以数组方式传递,例如：[id1, id2, id3, ...]
     * @param array $extendData  【根据积分账号类型决定是否填写】 积分赠送账号类型
     * [
     *        'area' => '[可选]区服ID',
     *        'platId' => '[可选]平台ID',
     *        'roleId' => '[可选]角色ID',
     *        'partition' => '[可选]区服ID',
     *        'sGameOpenid' => '[可选]游戏openid(默认取当前登录账号的openid)，查询非当前登录用户的积分时传递该值',
     *        'iPointType' => '积分账号类型：0-openid（默认），1-openid+area，2-openid+area+roleId，3-openid+platId，4-openid+area+partition'
     * ]
     *    积分账号分为四种类型(具体是那种类型可以跟活动跟进的开发人员或者产品确认)：
     *    0、openid，$extendData参数不需要传
     *    1、openid+area，$extendData = ['area'=>'渠道ID', 'iPointType'=>'1']
     *    2、openid+area+roleid，$extendData = ['area'=>'渠道ID', 'roleId'=>'角色ID','iPointType'=>'2']
     *    3、openid+platId，$extendData = ['platId'=>'平台ID', 'iPointType'=>'3']
     *    4、openid+area+partition，$extendData = ['area'=>'渠道ID', 'partition'=>'区服ID', 'iPointType'=>'4']
     *
     * @return array
     * [
     *      'iRet' => '0 成功 从data中获取积分信息，!=0 失败',
     *      'sMsg' => '系统消息',
     *      'sPaasSerial' => 'paas接口流水号'
     *      'data' =>
     *      [
     *          'id1' => ['point' => '剩余积分1', 'total' => '总积分1'],
     *          'id2' => ['point' => '剩余积分2', 'total' => '总积分2'],
     *          'id3' => ['point' => '剩余积分3', 'total' => '总积分3'],
     *          ...
     *      ]
     * ]
     */
    public function query($pointId, $extendData = [])
    {
        $apiName = '';
        if (is_array($pointId)) {
            foreach ($pointId as $id) {
                if (!Validate::checkNaturalNum($id)) {
                    return $this->getRetData('-1000500', '要查询的积分ID错误！');
                }
            }
            $apiName = 'point.batchquery';
        } else {
            $apiName = 'point.query';
            if (!Validate::checkNaturalNum($pointId)) {
                return $this->getRetData('-1000501', '要查询的积分ID错误！');
            }
        }

        $pointData = [];
        if (is_array($pointId)) {
            $pointData['pointIds'] = implode(',', $pointId);
        } else {
            $pointData['pointId'] = $pointId;
        }

        if (isset($extendData['iPointType']) && !in_array($extendData['iPointType'], ['0', '1', '2', '3', '4'])) {
            return $this->getRetData('-1', '积分账号类型错误！', []);
        }

        if (isset($extendData['area']) && Validate::checkArea($extendData['area'])) {
            $pointData['area'] = $extendData['area'];
        }

        if (isset($extendData['roleId']) && Validate::checkRoleId($extendData['roleId'], 2)) {
            $pointData['roleId'] = $extendData['roleId'];
        }

        if (isset($extendData['sGameOpenid']) && Validate::checkUin($extendData['sGameOpenid'])) {
            $pointData['sGameOpenid'] = $extendData['sGameOpenid'];
        }

        if (isset($extendData['iPointType']) && $extendData['iPointType'] == '3') {
            //openid + platId 账号类型，直接用platId 的值覆盖area
            if (!isset($extendData['platId']) || !in_array($extendData['platId'], ['0', '1'])) {
                return $this->getRetData('-2', '缺少平台ID参数！', []);
            } else {
                $pointData['platId'] = $extendData['platId'];
                $pointData['iPointType'] = $extendData['iPointType'];
            }
        }

        if (isset($extendData['iPointType']) && $extendData['iPointType'] == '4') {
            if (!Validate::checkArea($extendData['area']) || !Validate::checkPartition($extendData['partition'])) {
                return $this->getRetData('-3', '缺少渠道ID（area）或者区服ID（partition）！', []);
            }
            $pointData['area'] = $extendData['area'];
            $pointData['partition'] = $extendData['partition'];
            $pointData['iPointType'] = $extendData['iPointType'];
        }

        //url
        $url = $this->getPaasRequestUrl($apiName, $pointData);
        $res = $this->http->get($url);
        recordLog('积分查询paas接口返回值：' . var_export($res, true), __FILE__, __LINE__);

        if ($res['ret'] != 0) {
            $this->tglogReport('框架请求ULink-Paas出现异常，curl_errno：' . $res['ret'] . '，curl_error：' . $res['msg'], $apiName);
            return $this->getRetData(CURL_ERROR_NO, '系统繁忙，请稍后再试！');
        }
        $res = $res['data'];

        $rtnData['sPaasSerial'] = $res['sSerial'];
        if ($res['ret'] != 0) {
            return $this->getRetData($res['ret'], '系统繁忙，请稍后再试！', $rtnData);
        }

        if (is_array($pointId)) {
            $rtnData['data'] = $res['data'];
        } else {
            if ($res['data']['ret'] != 0) {
                return $this->getRetData($res['data']['ret'], '系统繁忙，请稍后再试！', ['sPaasSerial' => $res['sSerial']]);
            } else {
                $rtnData['data'][$pointId] = ['point' => $res['data']['point'], 'total' => $res['data']['total']];
            }
        }
        return $this->getRetData(0, 'success', $rtnData);
    }

    /**
     * 扣除积分
     * @param string $pointId 积分ID，请联系开发配置
     * @param int $num 要扣除的积分数量，默认为1
     * @param array $extendData  【根据积分账号类型决定是否填写】 积分赠送账号类型
     * [
     *        'area' => '[可选]大区',
     *        'platId' => '[可选]平台ID',
     *        'roleId' => '[可选]角色ID'
     *        'iPointType' => '积分账号类型：0-openid（默认），1-openid+area，2-openid+area+roleId，3-openid+platId'
     * ]
     *    积分账号分为四种类型(具体是那种类型可以跟活动跟进的开发人员或者产品确认)：
     *    0、openid，$extendData参数不需要传
     *    1、openid+area，$extendData = ['area'=>'渠道ID', 'iPointType'=>'1']
     *    2、openid+area+roleid，$extendData = ['area'=>'渠道ID', 'roleId'=>'角色ID','iPointType'=>'2']
     *    3、openid+platId，$extendData = ['platId'=>'平台ID', 'iPointType'=>'3']
     *    4、openid+area+partition，$extendData = ['area'=>'渠道ID', 'partition'=>'区服ID', 'iPointType'=>'4']
     *
     * @return array
     * [
     *      'iRet' => '=0-扣除成功， !=0 扣除失败',
     *      'sMsg' => '系统消息'
     * ]
     */
    public function reduce($pointId, $num = 1, $extendData = [])
    {
        $paasParam = ['pointId' => $pointId, 'num' => $num];

        if (isset($extendData['iPointType']) && !in_array($extendData['iPointType'], ['0', '1', '2', '3'])) {
            return $this->getRetData('-4', '积分账号类型错误！', []);
        }

        if (isset($extendData['area']) && Validate::checkArea($extendData['area'])) {
            $paasParam['area'] = $extendData['area'];
        }

        if (isset($extendData['roleId']) && Validate::checkRoleId($extendData['roleId'])) {
            $paasParam['roleId'] = $extendData['roleId'];
        }

        if (isset($extendData['iPointType']) && $extendData['iPointType'] == '3') {
            //openid + platId 账号类型，直接用platId 的值覆盖area
            if (!isset($extendData['platId']) || !in_array($extendData['platId'], ['0', '1'])) {
                return $this->getRetData('-5', '缺少平台ID参数！', []);
            } else {
                $paasParam['platId'] = $extendData['platId'];
                $paasParam['iPointType'] = $extendData['iPointType'];
            }
        }

        if (isset($extendData['iPointType']) && $extendData['iPointType'] == '4') {
            if (!Validate::checkArea($extendData['area']) || !Validate::checkPartition($extendData['partition'])) {
                return $this->getRetData('-6', '缺少渠道ID（area）或者区服ID（partition）！', []);
            }
            $pointData['area'] = $extendData['area'];
            $pointData['partition'] = $extendData['partition'];
            $pointData['iPointType'] = $extendData['iPointType'];
        }

        //url
        $url = $this->getPaasRequestUrl('point.reduce', $paasParam);
        $res = $this->http->get($url);
        recordLog('扣除积分接口返回值：' . var_export($res, true), __FILE__, __LINE__);

        if ($res['ret'] != 0) {
            $this->tglogReport('框架请求ULink-Paas出现异常，curl_errno：' . $res['ret'] . '，curl_error：' . $res['msg'], 'point.reduce');
            return $this->getRetData(CURL_ERROR_NO, '系统繁忙，请稍后再试！');
        }
        $res = $res['data'];
        if ($res['ret'] != 0 || $res['data']['ret'] != 0) {
            $iRet = $res['ret'] != 0 ? $res['ret'] : $res['data']['ret'];
            return $this->getRetData($iRet, '系统繁忙，请稍后再试！');
        } else {
            return $this->getRetData(0, 'success');
        }
    }
}
